const {ChatModel} =require('../bin/model')

module.exports = function (server) {
    // 得到 IO 对象
    const io = require('socket.io')(server, { cors: true })
    // 监视连接(当有一个客户连接上时回调)
    io.on('connection', function (socket) {
        console.log('soketio connected')
        // 绑定 sendMsg 监听, 接收客户端发送的消息
        socket.on('sendMsg', function (data) {
            console.log('服务端接收到客户端的消息:',data);
            const {from, to, content}=data
            const chat_id=[from,to].sort().join('_')
            const create_time=Date.now()
            new ChatModel({chat_id,create_time,content,from,to}).save((err,chatMsg)=>{
                io.emit("receiveMsg",{chatMsg})
            })
        })
    })
}